import React, { useState, useEffect, useRef } from 'react';
import { Link, history } from 'umi';
// import { CheckBox } from '@/components/CheckBox/CheckBox';
import { queryGetCoupon } from '@/services/coupon';
import { isEmpty, dateFormat } from '@/utils/common';
import moment from 'moment';
import { Message, SlideBox } from '@/design';
import styles from './getCoupon.less';

export default function (props:any) {

  const { className, second = false, canUse = true, canGet, canCheck, disabled, view = true, getCallback, showBtn, onUseCoupon } = props;
  const spinning = useRef(false);
  const userInfo = localStorage.getItem('userInfo');

  const [coupon, setCoupon] = useState<any>({});

  const [showRule, setShowRule] = useState(false);

  const [memberCheck, setMemberCheck] = useState(true);

  /* 領取優惠券 */
  const fetchGetCoupon = async (couponId: any) => {
 
    if(!memberCheck) {
      return Message.error('請勾選後再領取優惠券！');
    }
    if (isEmpty(userInfo)) {
      Message.error('請先登入賬號');
      history.push('/line');
      return;
    }
    const { userId = '' } = JSON.parse(userInfo || '{}');
    if (spinning.current) {
      return false;
    }
    spinning.current = true;
    let result:any = await queryGetCoupon(couponId, {userId });
    spinning.current = false;
    if (!result) return false;
    Message.success(result.message || '領取成功')
    getCallback && getCallback(couponId);
  }

  //优惠券时间
  const renderCouponTime = () => {
    const { timed } = props;
    const { validType, validDays, validStartTime, validEndTime } = coupon;
    if (timed && !isEmpty(validStartTime) && !isEmpty(validEndTime)) {
      if (moment(validStartTime).diff(moment()) > 0) {
        return `${dateFormat(validStartTime, 'YYYY-MM-DD')} - ${dateFormat(validEndTime, 'YYYY-MM-DD')}`
      } else if (moment(validEndTime).diff(moment()) > 0) {
        return `${moment(validEndTime).from(moment(), true)}後到期`
      } else {
        return `已過期`
      }
    } else {
      if (validType === 'relatively') {
        return `領取後${validDays}日內有效`
      } else {
        return `${dateFormat(validStartTime, 'YYYY-MM-DD')} - ${dateFormat(validEndTime, 'YYYY-MM-DD')}`
      }
    }
  }

  /* 查看詳情 */
  const linkToDetail = () => {
    if (!view) return false;
    if (coupon['canUse'] === '0' || coupon['canUse'] === 0) {
      return false;
    }
    if (!isEmpty(coupon['myCouponId'])) {
      history.push(`/coupon-detail?id=${coupon.myCouponId}`)
    }
  }

  useEffect(() => {
    if (!isEmpty(props.coupon)) {
      setCoupon(props.coupon)
    }
  }, [props.coupon])

  const handleMemberCheck = (e:any) => {
    setMemberCheck(!memberCheck)
  }

  return <div className={`${styles.coupon_card} ${second ? styles.second : ''} ${className ? className : ''} ${(coupon.couponStatus === 'used' || coupon.couponStatus === 'expired') || disabled ? styles.disabled : ''}`} >
    <div className={styles.coupon_wrap}>
      {/* 状态值 */}
      {/* <i className={styles.coupon_type}>
        {coupon.couponType === 'minus' && '滿減券'}
        {coupon.couponType === 'discount' && '折扣券'}
        {coupon.couponType === 'voucher' && '代金券'}
      </i> */}
      <div className={styles.coupon_price}>
        <p>
          {coupon.couponType != 'discount' && 'NT$ '}
          <span className={`${styles.price} ${(coupon.discountValue && coupon.discountValue.toString().length > 3) && styles.small}`}>{coupon.couponType != 'discount' ? coupon.discountValue : (coupon.discountValue / 10)}</span>
          {coupon.couponType === 'discount' && ' 折'}
        </p>
        <p>{coupon.useByAttainAmount > 0 ? `滿${coupon.useByAttainAmount}可用` : '無條件使用'}</p>
      </div>
      <div className={styles.coupon_info}>
        <div className={styles.info}>
          <h3>{props.couponName ? coupon.couponName : (coupon.braName || coupon.couponName)}</h3>
          <p>{renderCouponTime()}</p>
        </div>
        <div className={`${styles.rule} ${showRule ? styles.active : ''}`} onClick={!showBtn ? () => { setShowRule(!showRule) } : ()=>{}} >
          {
            showBtn && <div className={styles.tobeMer}>
            {/* <CheckBox pure checked={memberCheck} onChange={handleMemberCheck}>領取優惠券成為會員</CheckBox> */}
            </div>
          }
            <div onClick={!showBtn ? ()=>{} : () => { setShowRule(!showRule) }}>{disabled ? '* 不可使用原因' : showBtn ? '使用規則' : '優惠券使用規則'}</div>
        </div>
      </div>
      {coupon.couponStatus === 'usable' && (
        canCheck
          ?
          <div>勾选框</div>
          //  <CheckBox value={coupon.myCouponId} className={styles.check_box}></CheckBox>
          : !disabled && <a className={styles.status_unuse} onClick={onUseCoupon}>使用</a>)}
      {canGet &&
        ((coupon.issuedQuantity != 0 && coupon.issuedQuantity - coupon.peopleReceiveQuantity < 1) ?
          <a className={`${styles.disabled} ${styles.status_unuse}`} >領完</a>
          : (coupon.canReceive === '0'
            ? <a className={`${styles.disabled} ${styles.status_unuse}`} >已領</a>
            : <a className={`${styles.status_unuse}`}  onClick={() => { fetchGetCoupon(coupon.couponId) }}>領取</a>
          ))}
    </div>
    {!isEmpty(coupon) && <SlideBox className={styles.zIndex} key={`${coupon.braId}_${coupon.couponId}`} isShow={showRule}>
      <div className={styles.coupon_rule}>{disabled ? coupon.invalideReason : (coupon.remark || '暫無規則描述')}</div>
    </SlideBox>}
  </div>
}